<template>
  <div class="approved-by-me-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-card>
        <el-form :model="searchForm" inline>
          <el-form-item label="工作流名称">
            <el-input
              v-model="searchForm.workflowName"
              placeholder="请输入工作流名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="申请人">
            <el-input
              v-model="searchForm.creator"
              placeholder="请输入申请人"
              clearable
              style="width: 150px"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="工单状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
            >
              <el-option label="全部" value="" />
              <el-option label="运行中" value="running" />
              <el-option label="已暂停" value="pause" />
              <el-option label="待审批" value="approving" />
              <el-option label="已完成" value="complete" />
              <el-option label="已拒绝" value="reject" />
              <el-option label="已取消" value="cancel" />
            </el-select>
          </el-form-item>
          <el-form-item label="紧急程度">
            <el-select
              v-model="searchForm.priority"
              placeholder="请选择紧急程度"
              clearable
              style="width: 120px"
            >
              <el-option label="全部" :value="undefined" />
              <el-option label="紧急" :value="1" />
              <el-option label="普通" :value="0" />
              <el-option label="低" :value="-1" />
            </el-select>
          </el-form-item>
          <el-form-item label="审批时间">
            <el-date-picker
              v-model="searchForm.approvalDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :icon="Search">
              搜索
            </el-button>
            <el-button @click="handleReset" :icon="RefreshRight">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 已审批列表 -->
    <div class="table-container">
      <el-card>
        <template #header>
          <div class="card-header">
            <span class="card-title">我审批过的工单</span>
            <div class="header-actions">
            </div>
          </div>
        </template>

        <el-table
          :data="approvedList"
          v-loading="loading"
          stripe
          border
          style="width: 100%"
          @row-click="handleRowClick"
        >
          <el-table-column prop="workflowName" label="工作流名称" min-width="150">
            <template #default="{ row }">
              <div class="workflow-name-cell">
                <el-icon class="workflow-icon" color="#409eff">
                </el-icon>
                <span class="workflow-name">{{ row.workflowName }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="creator" label="申请人" width="120" />
          
          <el-table-column prop="status" label="状态" width="120">
            <template #default="{ row }">
              <el-tag 
                 :type="getStatusType(row.status)" 
                 :class="getStatusClass(row.status)"
                 size="small"
                 class="status-tag"
               >
                 <div class="status-content">
                   <span class="status-text">{{ getStatusLabel(row.status) }}</span>
                 </div>
               </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="currentNode" label="当前节点" width="120">
            <template #default="{ row }">
              <span class="current-node">{{ row.currentNodeName || '-' }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="priority" label="紧急程度" width="100">
            <template #default="{ row }">
              <el-tag :type="getPriorityType(row.priority)" size="small">
                {{ getPriorityLabel(row.priority) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="createdAt" label="申请时间" width="160">
            <template #default="{ row }">
              <span class="created-time">{{ formatDate(row.createTime) }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="updatedAt" label="更新时间" width="160">
            <template #default="{ row }">
              <span class="updated-time">{{ formatDate(row.updateTime) }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click.stop="handleViewDetail(row)"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 申请详情弹窗 -->
    <ApplicationDetailDialog
      v-model:visible="detailDialogVisible"
      :application="selectedApplication"
      source="approvedByMe"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, RefreshRight } from '@element-plus/icons-vue'
import { getApprovedByMe } from '/@/api/workflow'
import ApplicationDetailDialog from './components/ApplicationDetailDialog.vue'
import type { WorkflowInstance } from './types'

// 响应式数据
const loading = ref(false)
const approvedList = ref<WorkflowInstance[]>([])
const detailDialogVisible = ref(false)
const selectedApplication = ref<WorkflowInstance | null>(null)

// 搜索表单
const searchForm = reactive({
  workflowName: '',
  creator: '',
  status: '',
  priority: undefined as number | undefined,
  approvalDateRange: null as [string, string] | null
})

// 分页
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 方法
const fetchApprovedList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      size: pagination.size,
      workflowName: searchForm.workflowName || undefined,
      creator: searchForm.creator || undefined,
      status: searchForm.status || undefined,
      priority: searchForm.priority,
      approvalStartDate: searchForm.approvalDateRange?.[0] || undefined,
      approvalEndDate: searchForm.approvalDateRange?.[1] || undefined
    }
    
    const response = await getApprovedByMe(params)
    approvedList.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    ElMessage.error('获取已审批工单列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  fetchApprovedList()
}

const handleReset = () => {
  searchForm.workflowName = ''
  searchForm.creator = ''
  searchForm.status = ''
  searchForm.priority = undefined
  searchForm.approvalDateRange = null
  pagination.current = 1
  fetchApprovedList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  fetchApprovedList()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchApprovedList()
}

const handleRowClick = (row: WorkflowInstance) => {
  handleViewDetail(row)
}

const handleViewDetail = (row: WorkflowInstance) => {
  selectedApplication.value = row
  detailDialogVisible.value = true
}

// 状态相关方法
const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    running: 'primary',
    pause: 'warning',
    approving: 'warning',
    complete: 'success',
    reject: 'danger',
    cancel: 'info'
  }
  return typeMap[status] || 'info'
}

const getStatusLabel = (status: string) => {
  const labelMap: Record<string, string> = {
    running: '运行中',
    pause: '已暂停',
    approving: '待审批',
    complete: '已完成',
    reject: '已拒绝',
    cancel: '已取消'
  }
  return labelMap[status] || status
}

const getStatusClass = (status: string) => {
  return `status-${status}`
}

const getPriorityType = (priority: number) => {
  const typeMap: Record<number, string> = {
    1: 'danger',
    0: '',
    '-1': 'info'
  }
  return typeMap[priority] || ''
}

const getPriorityLabel = (priority: number) => {
  const labelMap: Record<number, string> = {
    1: '紧急',
    0: '普通',
    '-1': '低'
  }
  return labelMap[priority] || '普通'
}

const formatDate = (date: Date | string) => {
  if (!date) return '-'
  try {
    return new Date(date).toLocaleString('zh-CN')
  } catch {
    return '-'
  }
}

// 生命周期
onMounted(() => {
  fetchApprovedList()
})
</script>

<style scoped>
.approved-by-me-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 84px);
}

.search-container {
  margin-bottom: 20px;
}

.table-container {
  background: white;
  border-radius: 4px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 工作流名称样式 */
.workflow-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.workflow-icon {
  font-size: 16px;
}

.workflow-name {
  font-weight: 500;
  color: #303133;
}

/* 状态样式 */
:deep(.status-tag) {
  display: inline-flex !important;
  align-items: center !important;
  justify-content: center !important;
  min-width: 80px !important;
  padding: 4px 8px !important;
  text-align: center !important;
}

.status-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  width: 100%;
  text-align: center;
}

.status-icon {
  font-size: 12px;
  flex-shrink: 0;
  display: inline-flex;
  align-items: center;
}

.status-text {
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
  text-align: center;
  line-height: 1;
}

:deep(.status-running) {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  border-color: #409eff;
  color: white;
  animation: pulse 2s infinite;
}

:deep(.status-pause) {
  background: linear-gradient(135deg, #e6a23c 0%, #f0c78a 100%);
  border-color: #e6a23c;
  color: white;
}

:deep(.status-approving) {
  background: linear-gradient(135deg, #f56c6c 0%, #f89898 100%);
  border-color: #f56c6c;
  color: white;
  animation: blink 1.5s infinite;
}

:deep(.status-complete) {
  background: linear-gradient(135deg, #67c23a 0%, #95d475 100%);
  border-color: #67c23a;
  color: white;
}

:deep(.status-reject) {
  background: linear-gradient(135deg, #f56c6c 0%, #f89898 100%);
  border-color: #f56c6c;
  color: white;
}

:deep(.status-cancel) {
  background: linear-gradient(135deg, #909399 0%, #b1b3b8 100%);
  border-color: #909399;
  color: white;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.7);
  }
  70% {
    box-shadow: 0 0 0 6px rgba(64, 158, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
  }
}

@keyframes blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0.6;
  }
}

/* 时间样式 */
.created-time,
.updated-time {
  color: #606266;
  font-size: 13px;
}

.current-node {
  color: #303133;
  font-size: 13px;
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

@media (max-width: 768px) {
  .approved-by-me-container {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>